<template>
  <el-card>
    <div slot="header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item><a href="/">权限管理</a></el-breadcrumb-item>
        <el-breadcrumb-item><a href="/">角色列表</a></el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 主体内容 -->
    <div class="filter-bar">
      <div class="l-form"></div>
      <el-button
        type="primary"
        icon="el-icon-search"
        size="small"
        @click="isshow = true"
        >添加</el-button
      >
    </div>

    <!-- 表格区域 -->
    <div class="tab-list">
      <el-table :data="roleList" border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="item in scope.row.children"
              :key="item.id"
              class="line-row"
            >
              <el-col :span="7">
                <el-tag type="primary">{{ item.authName }}</el-tag>
              </el-col>
              <el-col :span="17">
                <el-row
                  v-for="value in item.children"
                  :key="value.id"
                  class="line-row"
                >
                  <el-col :span="8"
                    ><el-tag type="success">{{
                      value.authName
                    }}</el-tag></el-col
                  >
                  <el-col :span="16"
                    ><el-tag
                      v-for="val in value.children"
                      :key="val.id"
                      closable
                      type="warning"
                      @close="delSingle(scope.row, val.id)"
                      >{{ val.authName }}</el-tag
                    ></el-col
                  >
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="序号" align="center" type="index" width="130">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称" align="center">
        </el-table-column>
        <el-table-column prop="roleDesc" label="描述" align="center">
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="edit(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="del(scope.row.id)"
            ></el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="getList(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 弹出框 -->
    <el-dialog
      title="角色授权"
      :visible.sync="roleRightShow"
      width="30%"
      @close="closeDialog"
    >
      <!-- 树形图 -->
      <el-tree
        v-if="roleRightShow"
        ref="tree"
        :data="rightList"
        show-checkbox
        node-key="id"
        :props="{ label: 'authName', chlidren: 'chlidren' }"
        :default-checked-keys="defCheck"
        default-expand-all
      >
      </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="roleRightShow = false">取 消</el-button>
        <el-button type="primary" @click="roleSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
export default {
  data() {
    return {
      roleList: [],
      roleRightShow: false,
      rightList: [],
      defCheck: [], //三级角色ID
      roleid: null
    };
  },
  created() {
    this.getRoleList();
    this.getRightList();
  },
  methods: {
    async getRoleList() {
      let { data: res } = await this.$axios.get("roles");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      console.log(res);
      this.roleList = res.data;
    },
    // 删除角色
    async delSingle(row, rightId) {
      try {
        await this.$confirm("确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        });
        let { data: res } = await this.$axios.delete(
          `roles/${row.id}/rights/${rightId}`
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success("删除成功");
        // row表示当前行的数据， row.children所有权限，删除后返回所有数据
        row.children = res.data;
      } catch (error) {
        return this.$message.info("取消删除");
      }
    },
    getList(row) {
      this.roleRightShow = true;
      this.roleid = row.id;
      this.getLeafKeys(row, this.defCheck);
    },
    async getRightList() {
      let { data: res } = await this.$axios.get("rights/tree");
      //   判断是否获取成功
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      console.log(res);
      this.rightList = res.data;
    },
    getLeafKeys(node, arr) {
      //该函数会获取到当 前角色的所有三级权限id并添加到defKeys中
      //如果当前节点不包含children属性，则表示node为三级权限
      if (!node.children) {
        return arr.push(node.id);
      }
      //递归调用
      node.children.forEach(item => this.getLeafKeys(item, arr));
    },
    // 提交
    async roleSubmit() {
      // 获取所有全选和半选内容
      let authlist = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys()
      ];
      // 发送请求
      let { data: res } = await this.$axios.post(
        `roles/${this.roleid}/rights`,
        {
          rids: authlist.join(",")
        }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      console.log(res);
      this.$message.success("更新成功");
      this.getRoleList();
      this.roleRightShow = false;
    },
    // 关闭弹框
    closeDialog() {
      this.defCheck = [];
    }
  }
};
</script>

<style lang="less" scoped>
.line-row {
  padding: 10px 0;
}
</style>